package com.example.chat.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
@Slf4j
public class NettyServer {
    @Value("${websocket.netty.port}")
    private int port;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workGroup;

    /**
     * @description: 启动websocket服务
     */
    @PostConstruct
    public void start() {
        new Thread(() -> {
            try {
                bossGroup = new NioEventLoopGroup();
                workGroup = new NioEventLoopGroup();

                ServerBootstrap bootstrap = new ServerBootstrap();
                bootstrap.group(bossGroup, workGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new NettyInitializer())
                        .option(ChannelOption.SO_BACKLOG, 1024)
                        .childOption(ChannelOption.SO_KEEPALIVE, true)
                        .childOption(ChannelOption.TCP_NODELAY,true);

                ChannelFuture future = bootstrap.bind(port).sync();
                log.info("Websocket服务端启动成功，端口号：{}", port);

                future.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.error("Websocket服务端启动失败");
            }
        }).start();
    }

    /**
     * @description: 释放资源,容器销毁该组件之前被调用
     */
    @PreDestroy
    public void destroy() {
        if (Objects.nonNull(bossGroup)) {
            bossGroup.shutdownGracefully();
        }

        if (Objects.nonNull(workGroup)) {
            workGroup.shutdownGracefully();
        }
    }


}
